import os
import shutil  # 添加这一行
from flask import Flask, request, redirect, url_for, render_template, send_from_directory, flash
import datetime
app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 用于 session 加密
UPLOAD_FOLDER = 'uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 确保上传目录存在
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def index(path):
    full_path = os.path.join(app.config['UPLOAD_FOLDER'], path)
    try:
        items = os.listdir(full_path)
        files = []
        for item in items:
            item_path = os.path.join(full_path, item)
            is_dir = os.path.isdir(item_path)
            size = os.path.getsize(item_path) if not is_dir else 0
            modified_time = os.path.getmtime(item_path)
            files.append({
                'name': item,
                'is_dir': is_dir,
                'size': size,
                'modified_time': datetime.datetime.fromtimestamp(modified_time).strftime('%Y-%m-%d %H:%M:%S')
            })
    except FileNotFoundError:
        flash('路径不存在')
        return redirect(url_for('index'))
    
    return render_template('index.html', files=files, current_path=path)

@app.route('/upload', methods=['POST'])
def upload_file():
    current_path = request.form.get('current_path', '')
    full_path = os.path.join(app.config['UPLOAD_FOLDER'], current_path)
    
    if 'file' not in request.files:
        flash('没有选择文件')
        return redirect(url_for('index', path=current_path))
    
    file = request.files['file']
    if file.filename == '':
        flash('没有选择文件')
        return redirect(url_for('index', path=current_path))
    
    file.save(os.path.join(full_path, file.filename))
    return redirect(url_for('index', path=current_path))

@app.route('/create_folder', methods=['POST'])
def create_folder():
    folder_name = request.form.get('folder_name')
    current_path = request.form.get('current_path', '')
    full_path = os.path.join(app.config['UPLOAD_FOLDER'], current_path)
    
    if folder_name:
        os.makedirs(os.path.join(full_path, folder_name), exist_ok=True)
    return redirect(url_for('index', path=current_path))

@app.route('/delete/<path:filename>', methods=['POST'])
def delete_file(filename):
    current_path = request.form.get('current_path', '')
    file_path = os.path.join(app.config['UPLOAD_FOLDER'], current_path, filename)
    
    try:
        if os.path.isfile(file_path):
            os.remove(file_path)
        elif os.path.isdir(file_path):
            shutil.rmtree(file_path)  # 使用 shutil.rmtree 删除非空文件夹
    except Exception as e:
        flash(f'删除失败: {e}')
        
    return redirect(url_for('index', path=current_path))

@app.route('/download/<path:filename>', methods=['GET'])
def download_file(filename):
    current_path = request.args.get('current_path', '')
    return send_from_directory(os.path.join(app.config['UPLOAD_FOLDER'], current_path), filename, as_attachment=True)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=8021)
